<!-- 
人力资源统计 3 多项目
-->
<template>
  <ContainerLayout class="human-resource-statistics">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="部门" v-if="false">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="项目" v-if="false">
          <el-select v-model="projectValue" placeholder="请选择项目" style="width: 180px" :max-collapse-tags="1" multiple clearable collapse-tags>
            <template #header>
              <el-checkbox v-model="checkAllProject" :indeterminate="indeterminateProject" @change="handleCheckAllProject">全部</el-checkbox>
            </template>
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container" ref="tableContainer">
      <el-scrollbar :height="scrollbarHeight" always>
        <div v-for="tableItem in tableList" class="table-cells">
          <div class="table-title">{{ tableItem.tableTitle }}</div>
          <div class="table-wrap" ref="tableWrap">
            <el-table ref="dataTable" :data="tableItem.tableData" style="width: 100%" border scrollbar-always-on show-summary :summary-method="getSummaries" header-cell-class-name="table-header-row" empty-text="没有数据">
              <el-table-column prop="parentDeptName" label="地区" width="120" fixed />
              <el-table-column label="部门" width="150" fixed>
                <template #default="scope">
                  <div>{{ scope.row.deptName }}({{ scope.row.deptUserLength }})</div>
                </template>
              </el-table-column>
              <el-table-column prop="total" label="total" width="120" fixed>
                <template #default="scope">
                  <template v-if="scope.row.total">
                    <el-text v-if="scope.row.total < 0" type="danger">{{ scope.row.total }}</el-text>
                    <div v-else>{{ scope.row.total || 0 }}</div>
                  </template>
                  <div v-else>0</div>
                </template>
              </el-table-column>
              <el-table-column v-for="(item, index) in tableColumnDate" :prop="item.label" :key="index" width="120" resizable>
                <template #header>
                  <div class="table-header-cell">
                    <div>{{ item.label }}</div>
                  </div>
                </template>
                <template #default="scope">
                  <template v-if="scope.row[item.label]">
                    <el-text v-if="scope.row[item.label] < 0" type="danger">{{ scope.row[item.label] }}</el-text>
                    <div v-else>{{ scope.row[item.label] || 0 }}</div>
                  </template>
                  <div v-else>0</div>
                </template>
              </el-table-column>
              <el-table-column></el-table-column>
            </el-table>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </ContainerLayout>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, h } from 'vue'
import ContainerLayout from '../layout/ContainerLayout.vue'
import { Refresh, Search } from '@element-plus/icons-vue'
import type { CheckboxValueType } from 'element-plus'
import * as utils from '../utils'
import { useDeptStore, useProjectssStore } from '../stores'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import http from '../http'
import Api from '../api'

const deptCountMap = ref<any>({})
const deptList = ref(useDeptStore().getAllState())
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const projectValue = ref<CheckboxValueType[]>([])
const checkAllProject = ref(false)
const indeterminateProject = ref(false)
const tableList = ref<any>([])
const scrollbarHeight = ref(400)
const tableContainer = ref(ref<HTMLElement | null>(null))
// 表格是否查询过
const isQueryed = ref(false)
const tableData = ref<any[]>([])
const projectTitle = ref<string>('')
const weeks = ref()
const tableColumnDate = ref<any[]>([])
const tableRows = ref<any[]>([])
const rowsHeadcount = ref<any[]>([])
// 项目列表
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(useProjectssStore().getAllState() as any)
// 表单
const queryForm = reactive({
  user: '',
  projectId: '',
  date: [] as Date[],
  deptIds: [] as string[] | number[],
  timelogCategory: '',
})

onMounted(async () => {
  deptCountMap.value = await Api.Dept.getDeptUserCountMap()
  // await handleClickBtnReset()
  if (tableContainer.value) {
    scrollbarHeight.value = tableContainer.value.offsetHeight
  }
})
/**
 * 处理全选项目的逻辑
 *
 * @param val Checkbox 的值
 */
const handleCheckAllProject = (val: CheckboxValueType) => {
  indeterminateProject.value = false
  if (val) {
    projectValue.value = projectList.value.map((_) => _.id)
  } else {
    projectValue.value = []
  }
}

/**
 * 提交表单处理函数
 *
 * @returns {Promise<void>} 返回一个异步操作的Promise对象，无返回值
 */
const handleClickSubmit = async () => {
  // console.log('queryForm', queryForm)
  isQueryed.value = true
  tableData.value = []
  projectTitle.value = ''
  // console.log('queryForm.deptIds', queryForm.deptIds)

  if (queryForm.date.length == 2) {
    const [start, end] = queryForm.date
    weeks.value = utils.getWeeksBetweenDates(start, end)

    // 设置表格列
    await setTableColumn()
    await getDeptList()
    await buildDataTable()
  }
}
const handleClickBtnReset = async () => {
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.date = [start, end]
  await handleClickSubmit()
}

/**
 * 设置表格列
 *
 * @returns 无返回值
 */
const setTableColumn = async () => {
  // 设置 table 列
  tableColumnDate.value = []
  await new Promise((resolve) =>
    setTimeout(() => {
      tableColumnDate.value = [
        ...weeks.value.map((e: any) => {
          const start = utils.formatDate(e.start, 'yyyy-MM-dd')
          const end = utils.formatDate(e.end, 'yyyy-MM-dd')
          const startYear = utils.formatDate(e.start, 'yyyy')
          const endYear = utils.formatDate(e.end, 'yyyy')
          const startDay = utils.formatDate(e.start, 'MM-dd')
          const endDay = utils.formatDate(e.end, 'MM-dd')
          return { label: start, columnName: `${start} - ${end}`, start, end, startDay, endDay, startYear, endYear }
        }),
      ]
      resolve(true)
    }, 0)
  )
}
/**
 * 获取部门列表
 *
 * @returns 返回处理后的部门列表
 */
const getDeptList = async () => {
  const data = useDeptStore().getAllListState()
  const deptMap = new Map()
  const result: any = []

  // 先将所有部门信息存入Map，方便后续查找父部门名称
  data.forEach((item: any) => {
    deptMap.set(item.deptId, item)
  })

  data.forEach((item: any) => {
    const { deptId, parentId, deptName } = item
    const deptNamesExclude = '总经办,技术组'.split(',')
    if (parentId !== 100 && deptId !== 100 && deptNamesExclude.indexOf(deptName) === -1) {
      const parentItem = deptMap.get(parentId)
      const parentDeptName = parentItem.deptName
      result.push({ ...item, parentDeptName })
    }
  })

  tableRows.value = result
}

/**
 * 异步构建数据表格。
 *
 * @returns 无返回值。
 */
const buildDataTable = async () => {
  const tableData = await httpGetDataRow({
    path: '/dev-api/oa/timelog/listtr',
  })
  rowsHeadcount.value = tableData.pop()

  tableData.map(async (e: any) => {
    e.deptUserLength = deptCountMap.value[e.deptId]
  })
  tableList.value = [
    {
      tableTitle: '团队资源管理',
      tableData,
    },
  ]

  // let inter = setInterval(() => {
  //   const footers = document.querySelectorAll('.el-table__footer')
  //   if (footers.length == tableList.value.length) {
  //     footers.forEach((item: any) => {
  //       const tds = item.querySelectorAll('td')
  //       if (tds) {
  //         const tbs0 = tds[0] as HTMLElement
  //         tbs0.setAttribute('colspan', '2')
  //         tds[1].remove()
  //       }
  //       clearInterval(inter)
  //     })
  //   }
  // }, 200)
}

const httpGetDataRow = async (queryParams: any) => {
  const [first] = weeks.value
  const [last] = weeks.value.slice(-1)
  const startTimelogDate = utils.formatDate(first.start, 'yyyy-MM-dd')
  const endTimelogDate = utils.formatDate(last.end, 'yyyy-MM-dd')
  const params = {
    pageSize: 99999,
    startTimelogDate,
    endTimelogDate,
  }
  if (queryParams.params) {
    Object.assign(params, queryParams.params)
    delete queryParams.params
  }
  const defaultParams = {
    method: 'GET',
    path: ``,
    params,
  }
  Object.assign(defaultParams, queryParams)
  const res = await http(defaultParams)
  return res.rows
}
/**
 * 计算表格数据中的汇总信息
 *
 * @param param 包含表格列信息和数据的对象
 * @returns 返回汇总信息的数组，每个元素可能是字符串或VNode，表示该列的汇总结果
 */

const getSummaries = (param: any) => {
  const { columns } = param
  const sums: any[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = h('div', { class: 'total-headcount', style: 'width:270px;' }, ['Total Headcount'])
      return
    }
    if (index > 1 && column.property) {
      sums[index] = rowsHeadcount.value[column.property] || 0
    }
  })
  sums[1] = ''
  return sums
}
</script>
<style lang="scss" scoped>
.human-resource-statistics {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .table-header-cell {
    writing-mode: vertical-lr;
    // line-height: 1;
  }
  .table-cell {
    cursor: pointer;
    width: 100%;
  }
}
</style>
<style lang="scss">
.el-table__footer-wrapper tfoot td:first-child {
  z-index: 99;
  padding: 0;
  .cell {
    height: 40px;
    position: relative;
    overflow: visible;
  }
  .total-headcount {
    position: absolute;
    top: 0;
    left: 0;
    width: 200%;
    text-align: center;
    background-color: var(--el-table-row-hover-bg-color);
    height: auto;
    padding: 8px 0;
  }
}
</style>
